package svc

import (
	"context"
	"dfx_cmdb/cmdb-account-management-rpc/internal/config"
	cmdbaccountmanagement "dfx_cmdb/models/cmdb-account-management"

	toolsdatabase "gitee.com/daofeixian/dfx_golang_toolset/databases"
	toolsnosql "gitee.com/daofeixian/dfx_golang_toolset/nosqls"
	"github.com/zeromicro/go-zero/core/logc"
	"gorm.io/gorm"
)

type ServiceContext struct {
	Config config.Config
	PDB    *gorm.DB
	RC     toolsnosql.RedisClient
}

func NewServiceContext(c config.Config) *ServiceContext {
	cxt := context.Background()
	pdb, rc := initDBClient(cxt, c)
	autoMigrate(cxt, pdb, c)
	return &ServiceContext{
		Config: c,
		PDB:    pdb,
		RC:     rc,
	}
}

// autoMigrate 自动迁移数据库表结构
// 参数:
//   - cxt: 上下文对象
//   - pdb: PostgreSQL 数据库客户端
//   - c: 配置对象，判断是否开启自动迁移功能
func autoMigrate(cxt context.Context, pdb *gorm.DB, c config.Config) {
	// 如果启用了自动迁移，则执行模型的自动迁移操作
	if c.DBAUTO {
		err := pdb.AutoMigrate(&cmdbaccountmanagement.AccountManagement{})
		if err != nil {
			logc.Error(cxt, "数据库迁移失败")
		}
	}
}

func initDBClient(cxt context.Context, c config.Config) (pdb *gorm.DB, rc toolsnosql.RedisClient) {
	// 遍历数据库配置，初始化 PostgreSQL 和 ClickHouse 连接
	for _, v := range c.DatabasesConfig {
		if v.Type == "postgresql" && v.Name == "cmdb" {
			pdb = toolsdatabase.InitDBter(&v).InitDB()
			logc.Infof(cxt, "%s postgresql 链接成功", v.Host)
		}
	}
	// 遍历 Redis 配置，初始化指定名称的 Redis 客户端
	for _, v := range c.RedisConfig {
		if v.Name == "cmdb" {
			rc = toolsnosql.InitNosqlter(&v).InitRedis()
		}
	}
	return
}
